<template>
  <div class="customer-list-container">
    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stats-card stats-primary">
            <div class="stats-content">
              <div class="stats-info">
                <h3>{{ statistics.totalCount || 0 }}</h3>
                <p>总客户数</p>
              </div>
              <el-icon class="stats-icon" size="48">
                <User />
              </el-icon>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card stats-warning">
            <div class="stats-content">
              <div class="stats-info">
                <h3>{{ statistics.pendingCount || 0 }}</h3>
                <p>待审批</p>
              </div>
              <el-icon class="stats-icon" size="48">
                <Clock />
              </el-icon>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card stats-success">
            <div class="stats-content">
              <div class="stats-info">
                <h3>{{ statistics.approvedCount || 0 }}</h3>
                <p>已通过</p>
              </div>
              <el-icon class="stats-icon" size="48">
                <Check />
              </el-icon>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card stats-danger">
            <div class="stats-content">
              <div class="stats-info">
                <h3>{{ statistics.rejectedCount || 0 }}</h3>
                <p>已拒绝</p>
              </div>
              <el-icon class="stats-icon" size="48">
                <Close />
              </el-icon>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 操作区域 -->
    <el-card class="operation-card">
      <div class="operation-bar">
        <div class="operation-left">
          <el-button 
            v-if="isOfficeBusiness()"
            type="primary" 
            @click="showCreateDialog"
          >
            <el-icon><Plus /></el-icon>
            新增客户申请
          </el-button>
          <el-button @click="refreshAll">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
        <div class="operation-right">
          <el-input
            v-model="searchForm.customerName"
            placeholder="搜索客户名称..."
            style="width: 200px; margin-right: 10px;"
            clearable
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-select
            v-model="searchForm.approvalStatus"
            placeholder="全部状态"
            style="width: 120px; margin-right: 10px;"
            clearable
          >
            <el-option label="待审批" value="PENDING" />
            <el-option label="审批中" value="APPROVING" />
            <el-option label="已通过" value="APPROVED" />
            <el-option label="已拒绝" value="REJECTED" />
            <el-option label="已取消" value="CANCELLED" />
          </el-select>
          <el-button type="primary" @click="searchCustomers">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 客户列表 -->
    <el-card class="customer-list-card">
      <el-table
        :data="customerList"
        v-loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="客户ID" width="80" align="center" />
        <el-table-column prop="customerName" label="客户名称" width="150" show-overflow-tooltip />
        <el-table-column prop="contactPerson" label="联系人" width="100" />
        <el-table-column prop="phone" label="联系电话" width="130" />
        <el-table-column prop="email" label="邮箱" width="180" show-overflow-tooltip />
        <el-table-column prop="industry" label="行业" width="100" />
        <el-table-column prop="approvalStatus" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.approvalStatus)">
              {{ getStatusText(row.approvalStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="currentStep" label="当前步骤" width="120" show-overflow-tooltip />
        <el-table-column prop="customerCode" label="客户代码" width="120" />
        <el-table-column prop="createdAt" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="viewCustomerDetail(row)">
              查看详情
            </el-button>
            <!-- 申请人操作按钮 - 只有office_business用户可以使用 -->
            <el-button
              v-if="isOfficeBusiness() && row.approvalStatus === 'PENDING' && !row.processInstanceId"
              size="small"
              type="success"
              @click="submitCustomer(row.id)"
            >
              提交审批
            </el-button>
            <el-button
              v-if="isOfficeBusiness() && row.approvalStatus === 'PENDING' && !row.processInstanceId"
              size="small"
              type="warning"
              @click="editCustomer(row)"
            >
              编辑
            </el-button>
            <el-button
              v-if="isOfficeBusiness() && row.approvalStatus === 'PENDING' && !row.processInstanceId"
              size="small"
              type="danger"
              @click="cancelCustomer(row.id)"
            >
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 创建客户申请对话框 -->
    <CustomerApplicationForm
      v-model:visible="createDialogVisible"
      @success="handleCreateSuccess"
    />

    <!-- 客户详情对话框 -->
    <CustomerDetail
      v-model:visible="detailDialogVisible"
      :customer="currentCustomer"
      @success="handleDetailSuccess"
    />
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  User, Clock, Check, Close, Plus, Refresh, Search
} from '@element-plus/icons-vue'
import { getCustomerList, submitCustomerApplication, cancelCustomerApplication } from '../../api/customer.js'
import CustomerApplicationForm from './CustomerApplicationForm.vue'
import CustomerDetail from './CustomerDetail.vue'

export default {
  name: 'CustomerApplicationList',
  components: {
    User, Clock, Check, Close, Plus, Refresh, Search,
    CustomerApplicationForm,
    CustomerDetail
  },
  setup() {
    const loading = ref(false)
    const customerList = ref([])
    const statistics = ref({})
    const createDialogVisible = ref(false)
    const detailDialogVisible = ref(false)
    const currentCustomer = ref(null)
    
    const searchForm = reactive({
      customerName: '',
      approvalStatus: ''
    })
    
    const pagination = reactive({
      current: 1,
      size: 10,
      total: 0
    })
    
    // 加载客户列表
    const loadCustomers = async () => {
      try {
        loading.value = true
        const params = {
          page: pagination.current - 1,
          size: pagination.size,
          ...searchForm
        }
        
        const response = await getCustomerList(params)
        customerList.value = response.content || []
        pagination.total = response.totalElements || 0
      } catch (error) {
        console.error('加载客户列表失败:', error)
        ElMessage.error('加载客户列表失败')
      } finally {
        loading.value = false
      }
    }
    
    // 获取当前登录用户
    const getCurrentUser = () => {
      const userInfoStr = localStorage.getItem('userInfo')
      if (userInfoStr) {
        return JSON.parse(userInfoStr)
      }
      return null
    }
    
    // 检查当前用户是否为office_business
    const isOfficeBusiness = () => {
      const user = getCurrentUser()
      return user && user.username === 'office_business'
    }
    
    // 计算统计信息
    const calculateStatistics = () => {
      // 基于当前客户列表计算统计信息
      const totalCount = customerList.value.length
      const pendingCount = customerList.value.filter(customer => 
        customer.approvalStatus === 'PENDING'
      ).length
      const approvedCount = customerList.value.filter(customer => 
        customer.approvalStatus === 'APPROVED'
      ).length
      const rejectedCount = customerList.value.filter(customer => 
        customer.approvalStatus === 'REJECTED'
      ).length
      const approvingCount = customerList.value.filter(customer => 
        customer.approvalStatus === 'APPROVING'
      ).length

      statistics.value = {
        totalCount,
        pendingCount,
        approvedCount,
        rejectedCount,
        approvingCount
      }
      
      console.log('统计数据更新:', statistics.value)
    }
    
    // 搜索客户
    const searchCustomers = () => {
      pagination.current = 1
      loadCustomers()
    }
    
    // 刷新所有数据
    const refreshAll = async () => {
      try {
        loading.value = true
        ElMessage.info('正在刷新数据...')
        
        // 加载客户数据
        await loadCustomers()
        // 计算统计数据
        calculateStatistics()
        
        ElMessage.success('数据刷新成功')
      } catch (error) {
        console.error('刷新数据失败:', error)
        ElMessage.error('刷新数据失败')
      } finally {
        loading.value = false
      }
    }
    
    // 分页大小改变
    const handleSizeChange = (val) => {
      pagination.size = val
      pagination.current = 1
      loadCustomers()
    }
    
    // 当前页改变
    const handleCurrentChange = (val) => {
      pagination.current = val
      loadCustomers()
    }
    
    // 显示创建对话框
    const showCreateDialog = () => {
      createDialogVisible.value = true
    }
    
    // 查看客户详情
    const viewCustomerDetail = (customer) => {
      currentCustomer.value = customer
      detailDialogVisible.value = true
    }
    
    // 编辑客户
    const editCustomer = (customer) => {
      currentCustomer.value = customer
      createDialogVisible.value = true
    }
    
    // 提交客户审批
    const submitCustomerConfirm = async (customerId) => {
      try {
        await submitCustomerApplication(customerId)
        ElMessage.success('客户申请提交成功，已启动审批流程')
        await loadCustomers()
        calculateStatistics()
      } catch (error) {
        console.error('提交客户申请失败:', error)
        ElMessage.error('提交客户申请失败')
      }
    }
    
    // 取消客户申请
    const cancelCustomerConfirm = async (customerId) => {
      try {
        const { value: reason } = await ElMessageBox.prompt('请输入取消原因：', '取消客户申请', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /.+/,
          inputErrorMessage: '取消原因不能为空'
        })
        
        await cancelCustomerApplication(customerId, reason)
        ElMessage.success('客户申请已取消')
        await loadCustomers()
        calculateStatistics()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('取消客户申请失败:', error)
          ElMessage.error('取消客户申请失败')
        }
      }
    }
    
    // 获取状态类型
    const getStatusType = (status) => {
      const statusMap = {
        'PENDING': 'warning',
        'APPROVING': 'primary',
        'APPROVED': 'success',
        'REJECTED': 'danger',
        'CANCELLED': 'info'
      }
      return statusMap[status] || 'info'
    }
    
    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        'PENDING': '待审批',
        'APPROVING': '审批中',
        'APPROVED': '已通过',
        'REJECTED': '已拒绝',
        'CANCELLED': '已取消'
      }
      return statusMap[status] || status
    }
    
    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '-'
      return new Date(dateString).toLocaleString()
    }
    
    // 创建成功回调
    const handleCreateSuccess = () => {
      refreshAll()
    }
    
    // 详情操作成功回调
    const handleDetailSuccess = () => {
      refreshAll()
    }
    
    
    onMounted(async () => {
      await loadCustomers()
      calculateStatistics()
    })
    
    return {
      loading,
      customerList,
      statistics,
      searchForm,
      pagination,
      createDialogVisible,
      detailDialogVisible,
      currentCustomer,
      loadCustomers,
      calculateStatistics,
      searchCustomers,
      refreshAll,
      handleSizeChange,
      handleCurrentChange,
      showCreateDialog,
      viewCustomerDetail,
      editCustomer,
      submitCustomer: submitCustomerConfirm,
      cancelCustomer: cancelCustomerConfirm,
      getStatusType,
      getStatusText,
      formatDate,
      handleCreateSuccess,
      handleDetailSuccess,
      isOfficeBusiness
    }
  }
}
</script>

<style scoped>
.customer-list-container {
  padding: 20px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 60px);
}

.stats-cards {
  margin-bottom: 20px;
}

.stats-card {
  border: none;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s;
}

.stats-card:hover {
  transform: translateY(-2px);
}

.stats-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: white;
}

.stats-info h3 {
  margin: 0 0 5px 0;
  font-size: 2rem;
  font-weight: bold;
}

.stats-info p {
  margin: 0;
  font-size: 0.9rem;
  opacity: 0.9;
}

.stats-icon {
  font-size: 3rem;
  opacity: 0.8;
}

.stats-primary {
  background: linear-gradient(135deg, #409EFF, #66b1ff);
}

.stats-warning {
  background: linear-gradient(135deg, #E6A23C, #f0c78a);
}

.stats-success {
  background: linear-gradient(135deg, #67C23A, #95d475);
}

.stats-danger {
  background: linear-gradient(135deg, #F56C6C, #f89898);
}

.operation-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.operation-left {
  display: flex;
  gap: 10px;
}

.operation-right {
  display: flex;
  align-items: center;
}

.customer-list-card {
  min-height: 400px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

@media (max-width: 768px) {
  .operation-bar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .operation-left,
  .operation-right {
    justify-content: center;
  }
}
</style>
